package com.xiaoxu.intranetweb.mybatisplusSzappdb.controller.company;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.business.company.ContractBu;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.dao.UserInfoDao;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.SysFiles;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.entity.TCpyFiles;
import com.xiaoxu.intranetweb.mybatisplusSzappdb.excelEntity.CpyContractExcelEn;
import com.xiaoxu.intranetweb.util.PermissionCheck;
import com.xiaoxu.intranetweb.util.SzResult;
import com.xiaoxu.intranetweb.util.WebFunctionUtil;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.Future;

@RestController
@RequestMapping(value = "/contract")
public class ContractController {
    @Autowired
    private ContractBu contractBu;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private WebFunctionUtil webFunctionUtil;

    @PostMapping("/getCpyContract")
    @PermissionCheck("company_getCpyContract")
    public SzResult addCompany(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String cpyId = jsonObject.getString("cpyId");
        String startTime = jsonObject.getString("startTime");
        String endTime = jsonObject.getString("endTime");
        String contractName = jsonObject.getString("contractName");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return contractBu.getCpyContract(cpyId, startTime, endTime,contractName, plantId);
    }

    @PostMapping("/getCpyFile")
    @PermissionCheck("company_getCpyFile")
    public SzResult getCpyFile(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String cpyContractId = jsonObject.getString("cpyContractId");
        String token = request.getHeader("Authorization");
        return contractBu.getCpyFile(cpyContractId);
    }

    //新增合同
    @PostMapping("/addCpyContract")
    @PermissionCheck("company_addCpyContract")
    public SzResult addCpyContract(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String contractName = jsonObject.getString("contractName");
        String cpyId = jsonObject.getString("cpyId");
        String StartTime = jsonObject.getString("StartTime");
        String EndTime = jsonObject.getString("EndTime");
        String remark = jsonObject.getString("remark");
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        return contractBu.addCpyContract(contractName,cpyId,StartTime,EndTime,remark,token,plantId);
    }

    //上传文件
    @PostMapping("/upload")
    @PermissionCheck("cpy_file_upload")
    public SzResult upload(@RequestParam("file") MultipartFile file,
                           @RequestParam(required = false) String connId, HttpServletRequest request,
                           HttpServletResponse response) throws Exception {
        String token = request.getHeader("Authorization");
        return contractBu.uploadFile(file, connId, token);
    }
    //下载文件
    @GetMapping("/download")
    public void downloadFile(@RequestParam("fileId") String fileId, HttpServletResponse response, HttpServletRequest request) throws IOException {
        try {
            TCpyFiles tCpyFiles = contractBu.downloadFile(fileId);
            Path path = Paths.get(tCpyFiles.getFilePath() + tCpyFiles.getId() + "." + tCpyFiles.getFileType());
            String fileName = tCpyFiles.getFileName();
            InputStream inputStream = new BufferedInputStream(Files.newInputStream(new File(path.toString()).toPath()));
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/x-download");
            response.setHeader("Content-Length", "" + path.toFile().length());
            response.setHeader("Content-Disposition", "attachment; filename*=" + URLEncoder.encode(fileName, "UTF-8"));
            byte[] bytes = new byte[1024];
            int len = 0 ;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            response.setStatus(500);
            response.setContentType("application/json;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            e.printStackTrace();
        }
    }

    //删除文件
    @GetMapping("/deleteFile")
    @PermissionCheck("cpy_file_deleteFile")
    public SzResult deleteFile(@RequestParam("id") String id, HttpServletRequest request) throws Exception {
        try {
            return contractBu.deleteFile(id);
        } catch (Exception e) {
            e.printStackTrace();
            return SzResult.error(e.getMessage());
        }
    }

    //删除合同
    @GetMapping("/deleteCpyContract")
    @PermissionCheck("company_deleteCpyContract")
    public SzResult deleteCpyContract(@RequestParam("id") String id, HttpServletRequest request) throws Exception {
        try {
            return contractBu.deleteContract(id);
        } catch (Exception e) {
            e.printStackTrace();
            return SzResult.error(e.getMessage());
        }
    }
    //合同修改
    @PostMapping("/updateCpyContract")
    @PermissionCheck("company_updateCpyContract")
    public SzResult updateCpyContract(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        String id = jsonObject.getString("id");
        String contractName = jsonObject.getString("contractName");
        String cpyId = jsonObject.getString("cpyId");
        String StartTime = jsonObject.getString("StartTime");
        String EndTime = jsonObject.getString("EndTime");
        String remark = jsonObject.getString("remark");
        String token = request.getHeader("Authorization");
        return contractBu.updateCpyContract(id,contractName,cpyId,StartTime,EndTime,remark,token);
    }


    //    导出excel
    @PostMapping("/exportExcel")
    public void exportExcel(@RequestBody JSONObject jsonParam, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String token = request.getHeader("Authorization");
        String plantId = request.getHeader("Plant-Id");
        //        实体类
        List<Map<String, Object>> fields = jsonParam.getObject("fields", List.class);
//        文件名使用utf-8编码
        String filename = jsonParam.getString("filename");
//        数据
        List<Map<String, Object>> ids = jsonParam.getObject("ids", List.class);
//        是否有表头
        Boolean isHeader = jsonParam.getBoolean("isHeader");
//        mode为"current"时，导出当前页，为"all"时，导出所有页，selected时，导出选中数据
        String mode = jsonParam.getString("mode");
//        是否原始数据
        Boolean original = jsonParam.getBoolean("original");
//        分页
        Map<String, String> pager = jsonParam.getObject("pager", Map.class);
//        表格标题
        String sheetName = jsonParam.getString("sheetName");
        Map form = jsonParam.getObject("form", Map.class);
        Object o = form.get("cpyId");
        String cpyId = (o == null) ? null : o.toString();
        String startTime = Optional.ofNullable(form.get("startTime")).orElse("").toString();
        String endTime = Optional.ofNullable(form.get("endTime")).orElse("").toString();
        String contractName = Optional.ofNullable(form.get("contractName")).orElse("").toString();


        Future<List<CpyContractExcelEn>> listFuture = contractBu.exportExcel(fields, filename, ids, isHeader, mode, original, pager, sheetName, token, cpyId,startTime,endTime,contractName, plantId);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        BorderStyle borderStyle = BorderStyle.THIN;
        short borderColor = IndexedColors.BLACK.getIndex();
        contentWriteCellStyle.setBorderTop(borderStyle);
        contentWriteCellStyle.setBorderBottom(borderStyle);
        contentWriteCellStyle.setBorderLeft(borderStyle);
        contentWriteCellStyle.setBorderRight(borderStyle);
        contentWriteCellStyle.setTopBorderColor(borderColor);
        contentWriteCellStyle.setBottomBorderColor(borderColor);
        contentWriteCellStyle.setLeftBorderColor(borderColor);
        contentWriteCellStyle.setRightBorderColor(borderColor);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(null, contentWriteCellStyle);
        List<CpyContractExcelEn> cpyContractExcelEns = listFuture.get();
        response.setContentType("application/vnd.ms-excel; charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (filename == null || filename.isEmpty()) {
            filename = "单位合同";
        }
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8") + ".xlsx");
        EasyExcel.write(response.getOutputStream(), CpyContractExcelEn.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("单位合同").doWrite(cpyContractExcelEns);
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

}




